<template>
  <el-table
      ref="departmentTableRef"
      v-loading="isDepartmentsLoading"
      :cell-style="cellStyle"
      :data="departments"
      :tree-props="departmentTableProps"
      border
      default-expand-all
      height="250"
      highlight-current-row
      row-key="selfid"
      @current-change="handleDepartmentTableCurrentRowChange"
  >
    <el-table-column label="部门" prop="dept_name"/>
  </el-table>
  <el-table v-loading="isEmployeesToBeSelectedLoading" :data="employeesToBeSelected" border height="250">
    <el-table-column label="可选择的人员" prop="username"/>
    <el-table-column label="操作" width="100">
      <template #default="{row}">
        <el-button type="primary" @click="handleAddButtonClick(row)">添加</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-table :data="employeeSelected" border height="250">
    <el-table-column label="已选择的人员" prop="username"/>
    <el-table-column label="操作" width="100">
      <template #default="{row}">
        <el-button type="danger" @click="handleDeleteButtonClick(row)">移除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>
<script lang="ts" setup>
import {ref, watch} from "vue"
import {getDepartments as getDepartmentsFromApi} from "@/api/department";
import {DepartmentResponse2} from "@/api/types/department";
import {getEmployeesByDepartmentId} from "@/api/employee";
import {EmployeeResponse} from "@/api/types/employee";
import {ElMessage, ElTable} from "element-plus";

const props = defineProps<{
  filter?: "shop",
  initSelected?: { departmentId: number, userId: string }[],
  type: "userId" | "userIds"
}>()
const model = defineModel<string | string[]>()
const departments = ref<DepartmentResponse2[]>()
const departmentTableRef = ref<InstanceType<typeof ElTable>>()
const selectedDepartmentId = ref<number | undefined>()
const employeesToBeSelected = ref<EmployeeResponse[]>([])
const employeeSelected = ref<EmployeeResponse[]>([])
const isDepartmentsLoading = ref(false)
const isEmployeesToBeSelectedLoading = ref(false)

const departmentTableProps = {children: "childs"}
const cellStyle = {cursor: "pointer"}

watch(model, (newValue, oldValue) => {
  if (newValue === undefined && oldValue !== undefined) {
    employeeSelected.value = []
  }
})

watch(() => props.initSelected, (newValue) => {
  if (newValue !== undefined && newValue.length > 0) {
    employeeSelected.value = []
    newValue.forEach(async ({departmentId, userId}) => {
      const {data} = await getEmployeesByDepartmentId(departmentId)
      if (data !== undefined) {
        const employee = data.find(employee => employee.userid === userId)
        if (employee !== undefined) {
          employeeSelected.value.push(employee)
        }
      }
    })
  }
}, {
  immediate: true
})

function clearDepartmentSelection() {
  departmentTableRef.value?.setCurrentRow(undefined)
}

function clearEmployeesToBeSelected() {
  employeesToBeSelected.value = []
}

async function getDepartments() {
  if (isDepartmentsLoading.value === false) {
    isDepartmentsLoading.value = true
  }
  const {data} = await getDepartmentsFromApi()
  if (data?.info_list !== undefined) {
    departments.value = data.info_list
    isDepartmentsLoading.value = false
  }
}

getDepartments()

async function handleDepartmentTableCurrentRowChange({selfid}: DepartmentResponse2) {
  if (selfid !== undefined) {
    if (isEmployeesToBeSelectedLoading.value === false) {
      isEmployeesToBeSelectedLoading.value = true
    }
    const {data} = await getEmployeesByDepartmentId(selfid)
    if (data !== undefined) {
      // 当 filter 的值为 "shop" 时，可选择的人员里只显示办公地点为门店的人员
      employeesToBeSelected.value = data.filter(employee => {
        if (props.filter === "shop") {
          return employee.status === "已激活" && employee.locattionOfWork === "2"
        } else {
          return employee.status === "已激活"
        }
      })
      selectedDepartmentId.value = selfid
      isEmployeesToBeSelectedLoading.value = false
    }
  }
}

async function handleAddButtonClick(employee: EmployeeResponse) {
  if (props.type === "userId" && employeeSelected.value.length > 0) {
    ElMessage.warning("只能选择一名员工")
    return
  }
  if (!employeeSelected.value.some(existingEmployee => employee.userid === existingEmployee.userid)) {
    employeeSelected.value.push(employee)
    updateModel()
  } else {
    ElMessage.warning("已添加该员工，无需重复添加")
  }
}

async function handleDeleteButtonClick(employee: EmployeeResponse) {
  const indexOfEmployeeToBeDeleted = employeeSelected.value.findIndex(existingEmployee => employee.userid === existingEmployee.userid)
  if (indexOfEmployeeToBeDeleted !== -1) {
    employeeSelected.value.splice(indexOfEmployeeToBeDeleted, 1)
    updateModel()
  }
}

function updateModel() {
  switch (props.type) {
    case "userId": {
      model.value = employeeSelected.value[0].userid
      break
    }
    case "userIds": {
      model.value = employeeSelected.value.filter(employee => employee.userid !== undefined).map(employee => employee.userid!)
      break
    }
  }
}

defineExpose({clearDepartmentSelection, clearEmployeesToBeSelected})
</script>
